<?php
class Company {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 获取公司列表 (需要管理员权限)
     * @method GET
     * @route /company/list
     */
    public function list(): void {
        
        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(50, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = [];
        $params = [];
        
        if (!empty($_GET['keyword'])) {
            $keyword = '%' . $_GET['keyword'] . '%';
            $where[] = "(name LIKE :keyword OR address LIKE :keyword OR contact_phone LIKE :keyword)";
            $params[':keyword'] = $keyword;
        }

        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "status = :status";
            $params[':status'] = intval($_GET['status']);
        }

        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        // 查询总数
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM companies {$whereClause}");
        $stmt->execute($params);
        $total = $stmt->fetchColumn();

        // 查询数据
        $stmt = $this->conn->prepare("
            SELECT id, name, address, contact_phone, status, created_at, updated_at
            FROM companies
            {$whereClause}
            ORDER BY id DESC
            LIMIT :offset, :limit
        ");
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        
        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }

    /**
     * 创建公司 (需要超级管理员权限)
     * @method POST
     * @route /company/create
     */
    public function create(): void {
        $this->auth->checkSuperAdmin();
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['name'])) {
            throw new Exception("公司名称不能为空", 400);
        }

        // 检查公司名称是否已存在
        $stmt = $this->conn->prepare("SELECT id FROM companies WHERE name = :name LIMIT 1");
        $stmt->execute([':name' => $data['name']]);
        if ($stmt->fetch()) {
            throw new Exception("公司名称已存在", 409);
        }

        $time = time();

        // 准备公司数据
        $companyData = [
            ':name' => $data['name'],
            ':address' => $data['address'] ?? '',
            ':contact_phone' => $data['contact_phone'] ?? '',
            ':status' => $data['status'] ?? 1,
            ':created_at' => $time,
            ':updated_at' => $time
        ];

        // 插入公司数据
        $stmt = $this->conn->prepare("
            INSERT INTO companies (
                name, address, contact_phone, status, created_at, updated_at
            ) VALUES (
                :name, :address, :contact_phone, :status, :created_at, :updated_at
            )
        ");

        if (!$stmt->execute($companyData)) {
            throw new Exception("创建公司失败", 500);
        }

        $companyId = $this->conn->lastInsertId();

        // 返回创建成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '创建成功',
            'data' => [
                'company_id' => $companyId
            ]
        ]);
    }

    /**
     * 更新公司信息 (需要超级管理员权限)
     * @method POST
     * @route /company/update
     */
    public function update(): void {
        $this->auth->checkSuperAdmin();
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['id'])) {
            throw new Exception("缺少公司ID", 400);
        }

        // 检查公司是否存在
        $stmt = $this->conn->prepare("SELECT id FROM companies WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $data['id']]);
        if (!$stmt->fetch()) {
            throw new Exception("公司不存在", 404);
        }

        // 构建更新字段
        $updateFields = [];
        $params = [':id' => $data['id']];

        // 更新公司名称
        if (!empty($data['name'])) {
            // 检查公司名称是否已被其他公司使用
            $stmt = $this->conn->prepare("SELECT id FROM companies WHERE name = :name AND id != :id LIMIT 1");
            $stmt->execute([':name' => $data['name'], ':id' => $data['id']]);
            if ($stmt->fetch()) {
                throw new Exception("公司名称已被其他公司使用", 409);
            }
            
            $updateFields[] = "name = :name";
            $params[':name'] = $data['name'];
        }

        // 更新其他字段
        $optionalFields = ['address', 'contact_phone', 'status'];
        
        foreach ($optionalFields as $field) {
            if (isset($data[$field])) {
                $updateFields[] = "{$field} = :{$field}";
                $params[":{$field}"] = $data[$field];
            }
        }

        // 更新时间
        $updateFields[] = "updated_at = :updated_at";
        $params[':updated_at'] = time();

        if (count($updateFields) <= 1) { // 只有updated_at字段
            throw new Exception("没有可更新的字段", 400);
        }

        // 执行更新
        $sql = "UPDATE companies SET " . implode(', ', $updateFields) . " WHERE id = :id";
        $stmt = $this->conn->prepare($sql);
        
        if (!$stmt->execute($params)) {
            throw new Exception("更新公司信息失败", 500);
        }

        // 返回成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '更新成功'
        ]);
    }

    /**
     * 删除公司 (需要超级管理员权限)
     * @method POST
     * @route /company/delete
     */
    public function delete(): void {
        $this->auth->checkSuperAdmin();
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['id'])) {
            throw new Exception("缺少公司ID", 400);
        }

        // 检查公司是否存在
        $stmt = $this->conn->prepare("SELECT id FROM companies WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $data['id']]);
        if (!$stmt->fetch()) {
            throw new Exception("公司不存在", 404);
        }

        // 检查是否有用户关联该公司
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM users WHERE company_id = :company_id");
        $stmt->execute([':company_id' => $data['id']]);
        $userCount = $stmt->fetchColumn();

        if ($userCount > 0) {
            throw new Exception("该公司下还有用户，不能删除", 400);
        }

        // 执行删除
        $stmt = $this->conn->prepare("DELETE FROM companies WHERE id = :id");
        
        if (!$stmt->execute([':id' => $data['id']])) {
            throw new Exception("删除公司失败", 500);
        }

        // 返回成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '删除成功'
        ]);
    }

    /**
     * 获取公司详情 (需要管理员权限)
     * @method GET
     * @route /company/detail
     */
    public function detail(): void {
        $this->auth->checkAdmin();
        
        if (empty($_GET['id'])) {
            throw new Exception("缺少公司ID", 400);
        }

        $stmt = $this->conn->prepare("
            SELECT id, name, address, contact_phone, status, created_at, updated_at
            FROM companies
            WHERE id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $_GET['id']]);
        $company = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$company) {
            throw new Exception("公司不存在", 404);
        }

        // 返回公司详情
        echo json_encode([
            'code' => 200,
            'data' => $company
        ]);
    }
}